package com.whz.gateway.event;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * @author whz
 * @date 2021/8/25
 */
@Slf4j
@Component
public class AlertEventListener {
    public static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
        MAPPER.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
        MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    }

    @EventListener(GatewayAlertEvent.class)
    public void onAlert(GatewayAlertEvent event) {
        log.info("收到报警事件:{}", event);
        // TODO 报警
    }


    public static String toJson(Object message) {
        try {
            return MAPPER.writeValueAsString(message);
        } catch (Exception ignored) {
        }
        return "JSON ERROR";
    }
}